package cn.com.cifi.mars.util;

import java.beans.IntrospectionException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FieldUtils {

	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, IntrospectionException, InvocationTargetException {
		/*String name="smart-birthday";
		String value="ccccccccccccccccccc";
		IdmUser us=new IdmUser();
		setProperty(us, name.replaceAll("-", "_"),value);
		log.info(us.getSmart_birthday());*/
	}
	
	
	/* 该方法用于传入某实例对象以及对象方法名、修改值，通过放射调用该对象的某个set方法设置修改值 */
	public static void setProperty(Object beanObj,
			Object name,String value){
		try {
			Field[] fields = beanObj.getClass().getDeclaredFields();//获得属性
			Class clazz = beanObj.getClass();
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				Method setMethod = null;  
				Method [] methods = beanObj.getClass().getMethods();
				for(Method mtd : methods) {
					
					String setname=name.toString().substring(0,1).toUpperCase()+name.toString().substring(1,name.toString().length());
					if(mtd.getName().equals("set"+setname)) {
						setMethod = mtd;
					}
					if (setMethod != null) {
						
						if(field.getName().equals(name)) {
							//log.info(value+"进来了========="+name+"长度:"+value.length());
							//这里注意实体类中set方法中的参数类型，如果不是String类型则进行相对应的转换
							setMethod.invoke(beanObj, value);//invoke是执行set方法
						}
						//log.info(beanObj+"的字段是:"+field.getName()+"，参数类型是："+field.getType()+"，set的值是： "+value); 
					}
				}
				
				
			}
		} catch (SecurityException e) {
			 log.error("###### errorMsg: ", e);
		} catch (IllegalAccessException e) {
			 log.error("###### errorMsg: ", e);
		} catch (IllegalArgumentException e) {
			 log.error("###### errorMsg: ", e);
		} catch (InvocationTargetException e) {
			 log.error("###### errorMsg: ", e);
		}
	}

}
